import { Button, Drawer, Flex, Form, Input, Select, TimePicker } from "antd";
import { forwardRef, useImperativeHandle, useState } from "react";
import { updateTask, type DataItem } from "./api";
import { useRequest } from "ahooks";
import { getToken } from "../tokenManager/api";
import dayjs from "dayjs";

interface UpdateDrawerProps {
  onOk: () => void
}

export default forwardRef(function UpdateDrawer(props: UpdateDrawerProps, ref) {
  const { onOk } = props
  const [open, setOpen] = useState<boolean>(false);
  // const [isEdit, setIsEdit] = useState<boolean>(false);
  const [$form] = Form.useForm();

  const init = (data: DataItem) => {
    $form.setFieldsValue({
      ...data,
      userNames: data.userNames.split(','),
      taskTime: dayjs(data.taskTime, 'HH:mm:ss'),
    })
    // setIsEdit(true)
  }
  const handleOpen = (data: DataItem) => {
    setOpen(true);
    if (data) {
      init(data)
    }
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleOk = async () => {
    const values = await $form.validateFields();
    console.log(values);
    await updateTask({
      ...values,
      userNames: values.userNames.join(','),
      taskTime: dayjs(values.taskTime).format('HH:mm:ss'),
      createTime: new Date().toISOString()
    });
    handleClose();
    onOk()
  }

  useImperativeHandle(ref, () => ({
    open: handleOpen,
    close: handleClose,
  }));

  const { data: userOptions } = useRequest(async () => {
    const { message } = await getToken()
    return message.map(item => ({
      label: item.realName,
      value: item.userName
    }))
  })

  return <Drawer
    title="新增任务"
    onClose={handleClose}
    open={open}
    afterOpenChange={(open) => {
      if (!open) {
        $form.resetFields();
      }
    }}
    footer={<Flex gap={8} justify="end">
      <Button onClick={handleClose}>取消</Button>
      <Button type="primary" onClick={handleOk}>确认</Button>
    </Flex>}
  >
    <Form form={$form} labelCol={{ span: 6 }} colon={false}
    >
      <Form.Item
        label="id"
        name="id"
        hidden
      >
        <Input placeholder="请输入" />
      </Form.Item>
      <Form.Item
        label="任务名称"
        name="taskName"
        required
        rules={[{ required: true, message: '请输入' }]}
      >
        <Input placeholder="请输入" />
      </Form.Item>
      <Form.Item
        label="用户"
        name="userNames"
        required
        rules={[{ required: true, message: '请选择' }]}
      >
        <Select
          mode="multiple"
          options={userOptions}
          placeholder="请选择"
        />
      </Form.Item>

      <Form.Item
        label="任务时间"
        name="taskTime"
        required
        rules={[{ required: true, message: '请选择' }]}
      >
        <TimePicker
          changeOnScroll
          needConfirm={false}
          placeholder="请选择"
          style={{
            minWidth: '-webkit-fill-available'
          }}
        />
      </Form.Item>
    </Form>
  </Drawer>
})